'use strict';

const Service = require('egg').Service;

const data = [
  { id: '1', title: 'Read history of Node.js', completed: true },
  { id: '2', title: 'Learn Koa', completed: true },
  { id: '3', title: 'Star Egg', completed: false },
];

class TodoService extends Service {
  constructor(ctx) {
    super(ctx);
    this.store = data;
  }

  async index(filter = 'all') {
    const store = this.store;

    const actions = {
      completed: store.filter(v => v.completed),
      actively: store.filter(v => !v.completed),
      all: store,
    };

    const action = actions[filter] || actions.all;

    return action;
  }

  async create(data) {
    const id = Number.parseInt(this.store[this.store.length - 1].id) + 1;
    data.id = id.toString();
    this.store.push(data);

    return data.id;
  }

  async update(pid) {
    return this.store.some(function(item, index, array) {
      if (item.id !== pid) return false;
      array[index].completed = !array[index].completed;
      return true;
    });
  }

  async destroy() {
    this.store = [].concat(this.store.filter(item => !item.completed));
    console.log(this.store);
    return this.store.every(v => !v.completed);
  }
}

module.exports = TodoService;
